var express = require('express');
var router = express.Router();
var users = require('../models/users')
require('../util/util')

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});
//登陆接口
router.post('/login', function(req, res, next) {
    let userName = req.body.userName;
    let userPwd = req.body.userPwd;
    users.findOne({ userName: userName }, (userErr, userDoc) => {
        if (userErr) {
            res.json({
                status: 1,
                msg: "数据库错误"
            })
        } else {
            if (!userDoc) {
                res.json({
                    status: 1,
                    msg: "用户名错误，没有此用户"
                })
            } else {
                if (userPwd === userDoc.userPwd) {
                    res.cookie("userId", userDoc.userId, {
                        path: '/',
                        maxAge: 1000 * 60 * 60
                    });
                    res.cookie("userName", userDoc.userName, {
                        path: '/',
                        maxAge: 1000 * 60 * 60
                    });
                    res.json({
                        status: 0,
                        msg: '登录成功',
                        result: userDoc
                    })
                } else {
                    res.json({
                        status: 1,
                        msg: "密码错误，请从新输入"
                    })
                }
            }
        }
    })
});
//登出接口
router.post('/logout', function(req, res, next) {
    res.cookie("userId", "", {
        path: '/',
        maxAge: -1
    });
    res.cookie("userName", "", {
        path: '/',
        maxAge: -1
    });
    res.json({
        status: 0,
        msg: '登出成功',
        result: ''
    })
});
//检查登陆接口
router.get('/checkLogin', function(req, res, next) {
    if (req.cookies.userId) {
        res.json({
            status: 0,
            msg: '',
            result: req.cookies.userName
        })
    } else {
        res.json({
            status: 1,
            msg: '用户未登录',
            result: ''
        })
    }
});
//购物车接口
router.get('/cartlist', function(req, res, next) {
    let userId = req.cookies.userId;
    users.findOne({ userId: userId }, (err, doc) => {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: 'success',
                result: doc
            })
        }
    })
});
//购物车数量接口
router.post('/cartEdit', function(req, res, next) {
    let productNum = req.body.productNum;
    let userId = req.cookies.userId;
    let productId = req.body.productId;
    let checked = req.body.checked;
    //修改子文档
    users.update({ 'userId': userId, 'cartList.productId': productId }, { 'cartList.$.productNum': productNum, 'cartList.$.checked': checked }, function(err, doc) {
        if (err) {
            console.log(1)
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: "success",
                result: ""
            })
        }
    })
});

//删除接口
router.post('/cartDel', function(req, res, next) {
    let productId = req.body.productId;
    let userId = req.cookies.userId;
    //$pull删除数组其中一个 一层一层找
    users.update({ userId: userId }, { $pull: { 'cartList': { 'productId': productId } } }, function(err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: "success",
                result: ""
            })
        }
    })
});
//检查全选
router.post('/checkAll', function(req, res, next) {
    let checkFlag = req.body.checkFlag;
    let userId = req.cookies.userId;
    users.findOne({ userId: userId }, function(err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            doc.cartList.forEach(element => {
                element.checked = checkFlag ? '1' : '0';
            });
            doc.save(function(err, result) {
                if (err) {
                    res.json({
                        status: 1,
                        msg: '数据库错误',
                        result: ''
                    })
                } else {
                    res.json({
                        status: 0,
                        msg: "success",
                        result: ""
                    })
                }
            })
        }
    })
})

//获取地址列表
router.get('/address', function(req, res, next) {
    let userId = req.cookies.userId;
    users.findOne({ userId: userId }, function(err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: doc.addressList
            })
        }
    })
})

//设置默认地址
router.post('/setdefault', function(req, res, next) {
    let userId = req.cookies.userId;
    let addressId = req.body.addressId
    users.findOne({ userId: userId }, function(err, userDoc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            if (!userDoc) {
                res.json({
                    status: 2,
                    msg: '数据错误',
                    result: ''
                })
            } else {
                userDoc.addressList.forEach((item) => {

                    if (item.addressId == addressId) {
                        item.isDefault = true;
                    } else {
                        item.isDefault = false;
                    }
                })
                userDoc.save((err, doc) => {
                    if (err) {
                        res.json({
                            status: 1,
                            msg: '数据库错误',
                            result: ''
                        })
                    } else {
                        res.json({
                            status: 0,
                            msg: '',
                            result: ''
                        })
                    }
                })
            }
        }
    })
})

//删除地址
router.post('/delAddress', function(req, res, next) {
    let userId = req.cookies.userId;
    let addressId = req.body.addressId;
    users.update({ userId: userId }, { '$pull': { 'addressList': { 'addressId': addressId } } }, function(err, userdoc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: 'success',
                result: ''
            })
        }
    })
})


router.post('/payment', function(req, res, next) {
    let userId = req.cookies.userId;
    let addressId = req.body.addressId;
    let orderTotal = req.body.orderTotal;
    let addressInfo = {};
    let goodsList = [];
    if (!addressId || !orderTotal) {
        res.json({
            status: 1,
            msg: '参数错误',
            result: ''
        })
    } else {
        users.findOne({ userId: userId }, function(err, userdoc) {
            if (err) {
                res.json({
                    status: 1,
                    msg: '数据库错误',
                    result: ''
                })
            } else {
                userdoc.addressList.forEach(item => {
                    console.log(item.addressId, addressId)
                    if (item.addressId == addressId) {
                        console.log(1)
                        addressInfo = item;
                    }
                })
                userdoc.cartList.forEach(item => {
                    if (item.checked == 1) {
                        goodsList.push(item)
                    }
                })
                let global = '622';
                let r1 = Math.floor(Math.random() * 10);
                let r2 = Math.floor(Math.random() * 10);
                console.log(r1, r2)
                let datetime = new Date().Format('yyyyMMddhhmmss');
                let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
                let orderId = global + r1 + datetime + r2;
                let order = {
                    orderId: orderId,
                    orderTotal: orderTotal,
                    addressInfo: addressInfo,
                    goodsList: goodsList,
                    orderStatus: 1,
                    createDate: createDate
                }
                userdoc.orderList.push(order);
                userdoc.save(function(err, result) {
                    if (err) {
                        res.json({
                            status: 1,
                            msg: '数据库错误',
                            result: ''
                        })
                    } else {
                        res.json({
                            status: 0,
                            msg: 'success',
                            result: {
                                orderId: order.orderId,
                                orderTotal: order.orderTotal
                            }
                        })
                    }
                })
            }
        })
    }
})

router.get('/orderDetail', function(req, res, next) {
    let userId = req.cookies.userId;
    let orderId = req.query.orderId
    users.findOne({ userId: userId }, function(err, userdoc) {
        if (err) {
            res.json({
                status: 1,
                msg: '数据库错误',
                result: ''
            })
        } else {
            userdoc.orderList.forEach(item => {
                if (item.orderId == orderId) {
                    return res.json({
                        status: 0,
                        msg: 'success',
                        result: {
                            orderTotal: item.orderTotal
                        }
                    })
                }
            })
        }
    })
})

router.get('/getCartcount', function(req, res, next) {
    if (req.cookies && req.cookies.userId) {
        let userId = req.cookies.userId;
        let count = 0;
        users.findOne({ userId: userId }, function(err, doc) {
            if (err) {
                res.json({
                    status: 1,
                    msg: '数据库错误',
                    result: ''
                })
            } else {
                doc.cartList.map((item) => {
                    count += item.productNum
                })
                res.json({
                    status: 0,
                    msg: '',
                    result: count
                })
            }
        })
    } else {
        res.json({
            status: 1,
            msg: '用户名密码错误',
            result: ''
        })
    }
})
module.exports = router;